package com.alit.http.httpserver;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;

import lombok.extern.slf4j.Slf4j;

/**
 * @author litong
 * @date 2019年4月18日_下午2:00:01
 * @version 1.0
 */
@Slf4j
public class SocketChannelHandler implements Runnable {
	private SocketChannel socketChannel;

	public SocketChannelHandler(SocketChannel socketChannel) {
		this.socketChannel = socketChannel;
	}

	@Override
	public void run() {
		handle(socketChannel);
	}

	/**
	 * 接收SocketChanel中的数据
	 * 
	 * @param socketChannel
	 */
	private void handle(SocketChannel socketChannel) {
		ByteBuffer byteBuffer = ByteBuffer.allocate(2048);
		String string = null;
		try {
			socketChannel.read(byteBuffer);
			byteBuffer.flip();
			byte[] array = byteBuffer.array();
			string = new String(array);
		} catch (IOException e) {
			log.info("读取错我");
			e.printStackTrace();
		}finally {
			IOUtils.closeQuietly(socketChannel);
		}
		if (string != null) {
			DispatcherController dispatcherController = new DispatcherController();
			dispatcherController.dispatcher(string);
		} else {
			log.error("接收到空数据");
		}
	}
}
